package com.example.java.escape.thread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author : weicai
 * @date : 16:14 2020/11/27
 */
class SemaphoreDemo extends Thread {

    static Semaphore semaphore = new Semaphore(5);


    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            SemaphoreDemo demo = new SemaphoreDemo();
            demo.setName("线程" + i);
            demo.start();
        }
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + "---" + "获得许可");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        semaphore.release();
        System.out.println(Thread.currentThread().getName() + "---" + "离开了，剩余许可数量" + semaphore.availablePermits());
    }
}

